#include "LoadingScene.h"
#include "json\document.h"
#include "json\rapidjson.h"

LoadingScene* LoadingScene::createScene(const char *loadingFileName) {
	auto scene = new LoadingScene();
	if (scene && scene->initScene(loadingFileName)) {
		scene->autorelease();
		return scene;
	}
	CC_SAFE_DELETE(scene);
	return nullptr;
}

bool LoadingScene::initScene(const char *loadingFileName) {
	if (!Scene::init()) return false;
	auto rootNode = CSLoader::createNode(LOADINGSCENE_CSB_NAME);
	this->addChild(rootNode);

	m_loadingBar = rootNode->getChildByName<LoadingBar *>(LOADINGBAR);

	rapidjson::Document loadingList;
	loadingList.Parse<rapidjson::kParseDefaultFlags>(FileUtils::getInstance()->getStringFromFile(loadingFileName).c_str());
	rapidjson::Value &musicList = loadingList["music"];
	rapidjson::Value &plistList = loadingList["plist"];
	m_loadedResourse = 0;
	m_totalResourse = musicList.Size() + plistList.Size();

	for (unsigned int i = 0; i < musicList.Size(); i++) {
		AUDIOENGINE->preloadBackgroundMusic(musicList[i].GetString());
		m_loadedResourse++;
		m_loadingBar->setPercent((float)m_loadedResourse / (float)m_totalResourse);
	}

	for (unsigned int i = 0; i < plistList.Size(); i++) {
		SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistList[i].GetString());
		m_loadedResourse++;
		m_loadingBar->setPercent((float)m_loadedResourse / (float)m_totalResourse);
	}

	DIRECTOR->replaceScene(GameScene::create());
	
	return true;
}